package com.epfresh.supplier.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;

import com.epfresh.api.entity.RequestEntitySupply;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.global.BaseActivity;
import com.epfresh.api.global.BaseApplication;
import com.epfresh.api.http.HttpRequest;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.utils.FileUtil;
import com.epfresh.api.widget.tablayout.SlidingTabLayout;
import com.epfresh.api.widget.tablayout.listener.OnTabSelectListener;
import com.epfresh.supplier.R;
import com.epfresh.supplier.constant.Constant;
import com.epfresh.supplier.entity.OrderGroupRed;
import com.epfresh.supplier.fragment.*;
import com.google.gson.Gson;

import java.util.HashMap;
import java.util.Map;

public class OrderOnGroupActivity extends BaseActivity implements OnTabSelectListener {

    private SlidingTabLayout lyTab;
    private ViewPager vp;
    private OrderOnGroupFragment[] fragments;
    private int currentFragmentIndex;
    private boolean isFahuo = true;
    private boolean isShouhou = true;
    //    int pageCount;
//    int pageCountNew = 8;
    int orderType;
    private MyFragmentAdapter fragmentAdapter;
    private MyFragmentAdapter2 fragmentAdapter2;
    private boolean isFirst = false;
//    private String[] fragmentStates;//拼货中，
//    private String[] fragmentStatesNew = {"0","10","20","30","40","50","60",""};
    //String[] mTitles = new String[]{"拼货中", "付尾款", "待发货", "已发货", "待自提", "退款", "全部"};
//    String[] mTitles;
//    String[] mTitlesNew = new String[] {"待支付定金","拼货", "付尾款", "备货", "发货", "自提", "退款", "全部"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_agent);
        ivBack.setVisibility(View.VISIBLE);
        initData(savedInstanceState);
//        initView();
        vp = (ViewPager) findViewById(R.id.vp);
        lyTab = (SlidingTabLayout) findViewById(R.id.ly_navigation);
        requestOrderInfo();
//        initView();
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.righticon:
                Intent search = new Intent(this, OrderOnGroupSearchActivity.class);
                startActivity(search);
                break;
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        refreshList();

    }

    private void initData(Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            currentFragmentIndex = savedInstanceState.getInt(Constant.KEY_HOME_STATE_INDEX);
            getIntent().putExtra("orderType", savedInstanceState.getInt("orderType"));
        }

        orderType = getIntent().getIntExtra("orderType", 0);
        fragmentAdapter = new MyFragmentAdapter(getSupportFragmentManager());
        fragmentAdapter2 = new MyFragmentAdapter2(getSupportFragmentManager());
    }

    private void initView(final int pageCount, final String[] fragmentStates, String[] mTitles) {
        ivBack.setVisibility(View.VISIBLE);
        righticon.setImageResource(R.mipmap.order_search);
        righticon.setVisibility(View.VISIBLE);
        righticon.setOnClickListener(this);
        tvBack.setVisibility(View.VISIBLE);
//        vp = (ViewPager) findViewById(R.id.vp);
//        lyTab = (SlidingTabLayout) findViewById(R.id.ly_navigation);
        setToolbarTitle("拼货订单");


        lyTab.setOnTabSelectListener(this);
        vp.setOffscreenPageLimit(pageCount);
        vp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                currentFragmentIndex = position;
                lyTab.onPageSelected(position);
                if (pageCount == 6) {
                    if (position == 2) {
                        lyTab.showRedFlag(position, false);
                        isFahuo = false;
                    }
                    if (position == 4) {
                        lyTab.showRedFlag(position, false);
                        isShouhou = false;
                    }

                } else if (pageCount == 7) {
                    if (position == 3) {
                        lyTab.showRedFlag(position, false);
                        isFahuo = false;
                    }
                    if (position == 5) {
                        lyTab.showRedFlag(position, false);
                        isShouhou = false;
                    }

                }

               /* int selfIndex = 3;
                if (pageCount == 6) {

                } else if (pageCount == 7) {
                    if (position == 1 || position == 2 || position == 3 || position == 5){
                        lyTab.showRedFlag(position,false);
                    }
                }

                if(position==3) {
                    lyTab.showRedFlag(position,false);
                    if (responseElement == null) {
                        return;
                    }else{
                        SharedPreferences sp = FileUtil.getSharedPreferences();
                        String flag = sp.getString("group_goods_red_flag", "");
                        if(flag.equals(responseElement.getReceiveGoodsId())){
                            return;
                        }else{
                            SharedPreferences.Editor editor = sp.edit();
                            editor.putString("group_goods_red_flag", responseElement.getReceiveGoodsId());
                            editor.commit();
                        }
                    }
                }
                if(position==5){
                    lyTab.showRedFlag(position,false);
                    if (responseElement == null) {
                        return;
                    }else{
                        SharedPreferences sp = FileUtil.getSharedPreferences();
                        String flag = sp.getString("group_refund_red_flag", "");
                        if(flag.equals(responseElement.getReceiveGoodsId())){
                            return;
                        }else{
                            SharedPreferences.Editor editor = sp.edit();
                            editor.putString("group_refund_red_flag", responseElement.getRefundId());
                            editor.commit();
                        }
                    }
                }*/
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        vp.setAdapter(fragmentAdapter);
        fragmentAdapter.setData(pageCount, fragmentStates);
        fragmentAdapter.notifyDataSetChanged();

        lyTab.setViewPager(vp, mTitles);
        vp.setCurrentItem(currentFragmentIndex);

    }

    class MyFragmentAdapter extends FragmentStatePagerAdapter {
        int pageCount;
        String[] fragmentStates;

        public MyFragmentAdapter(FragmentManager fm) {
            super(fm);

        }

        public void setData(int pageCount, String[] fragmentStates) {
            this.pageCount = pageCount;
            this.fragmentStates = fragmentStates;
        }

        @Override
        public Fragment getItem(int position) {
            int i = 4;
            if (pageCount == 6) {
                i = 4;
            } else if (pageCount == 7) {
                i = 5;
            }
            if (position != i) {
                if (fragments[position] == null)
                    fragments[position] = new OrderOnGroupFragment(fragmentStates[position]);
//                    currentFragmentIndex = position;
                return fragments[position];
            } else {
                if (fragments[position] == null || fragments[position] instanceof OrderOnGroupFragment)
                    fragments[position] = new OrderOnGroupMinusFragment();
//                        currentFragmentIndex = position;
                return fragments[position];
            }
        }

        @Override
        public int getCount() {
            return pageCount;
        }

        @Override
        public int getItemPosition(Object object) {
            return PagerAdapter.POSITION_NONE;
        }
    }

    class MyFragmentAdapter2 extends FragmentPagerAdapter {
        int pageCount;
        String[] fragmentStates;

        public MyFragmentAdapter2(FragmentManager fm) {
            super(fm);

        }

        public void setData(int pageCount, String[] fragmentStates) {
            this.pageCount = pageCount;
            this.fragmentStates = fragmentStates;
        }

        @Override
        public Fragment getItem(int position) {
            int i = 4;
            if (pageCount == 6) {
                i = 4;
            } else if (pageCount == 7) {
                i = 5;
            }
            if (position != i) {
                if (fragments[position] == null)
                    fragments[position] = new OrderOnGroupFragment(fragmentStates[position]);
//                    currentFragmentIndex = position;
                return fragments[position];
            } else {
                if (fragments[position] == null || fragments[position] instanceof OrderOnGroupFragment)
                    fragments[position] = new OrderOnGroupMinusFragment();
//                        currentFragmentIndex = position;
                return fragments[position];
            }
        }

        @Override
        public int getCount() {
            return pageCount;
        }
    }


    @Override
    public void onTabSelect(int position) {
        vp.setCurrentItem(position);
        if (position < fragments.length && fragments[position] != null) {
            fragments[position].refresh();
        }
    }

    //再次点击当前选中的tab
    @Override
    public void onTabReselect(int position) {

    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        //记录当前fragment的下标
        outState.putInt(Constant.KEY_HOME_STATE_INDEX, currentFragmentIndex);
        outState.putInt("orderType", orderType);
        super.onSaveInstanceState(outState);
    }

    public void refreshList() {
        if (fragments[currentFragmentIndex] != null)
            fragments[currentFragmentIndex].refresh();
    }

/*    public void refreshList() {
        if (fragments[currentFragmentIndex] != null&&fragments[currentFragmentIndex] instanceof OrderOnGroupFragment)
            ((OrderOnGroupFragment)fragments[currentFragmentIndex]).refresh();
        else{
            ((OrderOnGroupMinusFragment)fragments[currentFragmentIndex]).refresh();
        }
    }*/


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            refreshList();
        }
    }


    private boolean isFirstInit = true;
    OnRequestListener<OrderGroupRed> onRequestListener = new OnRequestListener<OrderGroupRed>() {
        @Override
        public OrderGroupRed jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, OrderGroupRed.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
        }

        @Override
        public void onStart(Object tag) {
        }

        @Override
        public void onResponse(ResponseEntity<OrderGroupRed> response, Object tag) {
            responseElement = response.getResponseElement();

            if (isFirstInit) {
                fragments = null;
                String[] mTitles;
                String[] fragmentStates;
                int pageCount;

                if (!responseElement.isGrouponCnt()) {
                    fragmentStates = new String[]{"10", "20", "40", "50", "60", ""};
                    mTitles = new String[]{"拼货", "付尾款", "发货", "自提", "售后", "全部"};
                    pageCount = 6;
                    num = 0;

                    fragments = new OrderOnGroupFragment[6];
//                fragments = new OrderOnGroupFragment[]{
//                        new OrderOnGroupFragment("10"),
//                        new OrderOnGroupFragment("20"),
//                        new OrderOnGroupFragment("40"),
//                        new OrderOnGroupFragment("50"),
//                        new OrderOnGroupMinusFragment(),
//                        new OrderOnGroupFragment()};
                } else {
                    fragmentStates = new String[]{"0", "10", "20", "40", "50", "60", ""};
                    mTitles = new String[]{"待支付订金", "拼货", "付尾款", "发货", "自提", "售后", "全部"};
                    pageCount = 7;
                    num = 1;

                    fragments = new OrderOnGroupFragment[7];
//                fragments = new OrderOnGroupFragment[]{
//                        new OrderOnGroupFragment("0"),
//                        new OrderOnGroupFragment("10"),
//                        new OrderOnGroupFragment("20"),
//                        new OrderOnGroupFragment("40"),
//                        new OrderOnGroupFragment("50"),
//                        new OrderOnGroupMinusFragment(),
//                        new OrderOnGroupFragment()};
                }
                initView(pageCount, fragmentStates, mTitles);
                isFirstInit = false;
            }


//            lyTab.showRedFlag(0,responseElement.isGrouponCnt());
            lyTab.showRedFlag(1 + num, responseElement.isLastPayCnt());
            lyTab.showRedFlag(3 + num, responseElement.isPickupCnt());

            if (responseElement.getReceiveGoodsId() == null || "".equals(responseElement.getReceiveGoodsId())) {
                lyTab.showRedFlag(2 + num, false);
            } else {
                SharedPreferences sp = FileUtil.getSharedPreferences();
                String flag = sp.getString("group_goods_red_flag", "");
                if (flag.equals(responseElement.getReceiveGoodsId())) {
                    lyTab.showRedFlag(2 + num, false);
                } else {
                    lyTab.showRedFlag(2 + num, true);
                }
                if (!isFahuo) {
                    lyTab.showRedFlag(2 + num, false);
                } else {
                    lyTab.showRedFlag(2 + num, true);
                }
            }

            if (responseElement.getRefundId() == null || "".equals(responseElement.getRefundId())) {
                lyTab.showRedFlag(4 + num, false);
            } else {
                SharedPreferences sp = FileUtil.getSharedPreferences();
                String flag = sp.getString("group_refund_red_flag", "");
                if (flag.equals(responseElement.getRefundId())) {
                    lyTab.showRedFlag(4 + num, false);
                } else {
                    lyTab.showRedFlag(4 + num, true);
                }
                if (!isShouhou) {
                    lyTab.showRedFlag(4 + num, false);
                } else {
                    lyTab.showRedFlag(4 + num, true);
                }
            }

        }
    };

    String cmdOrderDetails = "pm-order/baseorder/order/redDot";
    OrderGroupRed responseElement;
    int num = 0;//小红点往后错一位

    public void requestOrderInfo() {
        RequestEntitySupply<Map<String, String>> entity = new RequestEntitySupply<>();
        entity.setCmd(cmdOrderDetails);
        Map<String, String> map = new HashMap<>();
        map.put("buyerStoreId", BaseApplication.getInstance().getStoreId());
        entity.setParameters(map);
        request(entity, cmdOrderDetails, onRequestListener);
    }
}
